#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2023/4/13 12:09
# @Author  : 胡浩浩
# @Email   : hu_haohao@venusgroup.com.cn
# @File    : comms.py
# @IDE     : PyCharm
# @description :
import os
import re
import uuid

from pywebio.output import close_popup, toast
from pywebio.session import eval_js


def generate_random_string(length):
    """
    获取指定长度的随机字符串
    """
    import random
    import string
    # Define the possible characters to choose from
    letters = string.ascii_lowercase
    # Use random.choices to select `length` number of characters from `letters`
    result_str = ''.join(random.choices(letters, k=length))
    return result_str


def generate_uuid():
    return str(uuid.uuid4())


def close_pop():
    close_popup()
    eval_js("window.location.reload();")


def error_toast(data):
    toast(str(data), color="red")
    return data


def check_actually_data(data):
    check_result = None
    if not data:
        error_data = error_toast("请输入数据再进行操作")
        check_result = error_data
    return check_result


def get_all_files(path):
    files = os.listdir(path)
    result = []
    for file in files:
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            result.extend(get_all_files(file_path))
        else:
            result.append(file_path)
    return result


def validate_ip(ip, file_name):
    # IP 地址的正则表达式模式
    pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$'

    if re.match(pattern, ip):
        return ip
    else:
        error_toast(f"{file_name}格式不正确")
        return False


def validate_port(port, file_name):
    # 端口号的正则表达式模式
    pattern = r'^[1-9]\d*$'

    if re.match(pattern, port) and 0 < int(port) <= 65535:
        return port
    else:
        error_toast(f"{file_name}格式不正确")
        return False


def validate_url(url, file_name):
    # 网址的正则表达式模式
    pattern = r'^https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'

    if re.match(pattern, url):
        return url
    else:
        error_toast(f"{file_name}地址格式错误")
        return False


def is_not_empty(s, file_name):
    """
    判断字符串是否非空

    :param file_name: 字段中文名称
    :param s: 待校验的字符串
    :return: True 表示非空，False 表示为空
    """
    if isinstance(s, str) and s.strip():
        return s
    elif isinstance(s, int):
        return s
    elif isinstance(s, list) and len(s)>0:
        return s
    else:
        error_toast(f"{file_name}不能为空")
        return False
